package com.chap9;

import ch.qos.logback.core.encoder.EchoEncoder;

import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-03-25
 * Time: 5:15
 * To change this template use File | Settings | File Templates.
 */
public class CopyOnWriteArrayListDemo {
    private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

    static{
        //模拟初始化的黑名单数据
        list.add("ipAddr0");
        list.add("ipAddr1");
        list.add("ipAddr2");
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                //模拟接入用时
                try{
                    Thread.sleep(new Random().nextInt(5000));
                }catch (Exception e){
                }
                String currentIP = "ipAddr"+ new Random().nextInt(6);
                if (list.contains(currentIP)){
                    System.out.println(Thread.currentThread().getName()+" IP "+currentIP+" 命中黑名单，拒绝接入处理");
                    return;
                }
                System.out.println(Thread.currentThread().getName()+" IP "+currentIP+"接入处理...");
            }
        };

        new Thread(task,"请求1").start();
        new Thread(task,"请求2").start();
        new Thread(task,"请求3").start();

        new Thread(()->{
            try {
                Thread.sleep(new Random().nextInt(2000));
            } catch (InterruptedException e) {
            }
            String newBlackIP = "ipAddr3";
            list.add(newBlackIP);
            System.out.println(Thread.currentThread().getName() + " 添加了新的非法IP " + newBlackIP);
        },"IP黑名单更新").start();
        Thread.sleep(1000000);
    }
}
